package top.milkbox.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.milkbox.common.bo.EntityColumnExistence;
import top.milkbox.common.service.CommonService;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * 抽取通用服务<br />
 * 创建时间: 2024-02-04 下午 2:26
 *
 * @author milkbox
 */
public class CommonServiceImpl<M extends BaseMapper<E>, E> extends ServiceImpl<M, E> implements CommonService<E> {

    @Override
    public <T extends Serializable> EntityColumnExistence<T> filterDoesNotExistColumn(
            SFunction<E, T> column, Collection<T> entityColumnCollection) {
        if (ObjectUtil.isEmpty(entityColumnCollection)) {
            return new EntityColumnExistence<>(Collections.emptyList(), Collections.emptyList());
        }
        // 创建可见性对象，用于存储存在的和不存在的实体列集合
        EntityColumnExistence<T> entityColumnExistence = new EntityColumnExistence<>();
        // 查询并保存存在的实体列
        LambdaQueryWrapper<E> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(column, entityColumnCollection);
        entityColumnExistence.setExistColumnList(super.list(queryWrapper).stream().map(column).toList());
        // 在原实体中移除已经存在的实体
        // 注意：removeAll方法仅支持可变类型的集合，即ArrayList类型
        ArrayList<T> entityColumnList = new ArrayList<>(entityColumnCollection);
        entityColumnList.removeAll(entityColumnExistence.getExistColumnList());
        // 将不存在的id集合保存到可见性对象
        entityColumnExistence.setDoesNotExistColumnList(entityColumnList);
        return entityColumnExistence;
    }
}
